
Component({
  options: {
    addGlobalClass: true,
    multipleSlots: true
  },
  /**
   * 组件的属性列表
   */
  properties: {
    name: {
      type: [String, Number],
      value: ""
    },
    value: {
      type: [String, Number],
      value: 0
    },
    min: {
      type: [String, Number],
      value: 1
    },
    max: {
      type: [String, Number],
      value: 100
    },
    step: {
      type: [String, Number],
      value: 1
    },
    integer: {
      type: Boolean,
      value: false
    },
    disabled: {
      type: Boolean,
      value: false
    },
    disabledInput: {
      type: Boolean,
      value: false
    },
    asyncChange: {
      type: Boolean,
      value: false
    },
    inputWidth: {
      type: [String, Number],
      value: 40
    },
    showMinus: {
      type: Boolean,
      value: true
    },
    showPlus: {
      type: Boolean,
      value: true
    },
    decimalLength: {
      type: [String, Number, null],
      value: 0
    },
    longPress: {
      type: Boolean,
      value: true
    },
    color: {
      type: String,
      value: "#323233"
    },
    buttonSize: {
      type: [String, Number],
      value: 30
    },
    bgColor: {
      type: String,
      value: "#EBECEE"
    },
    cursorSpacing: {
      type: [String, Number],
      value: 100
    },
    disablePlus: {
      type: Boolean,
      value: false
    },
    disableMinus: {
      type: Boolean,
      value: false
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    currentValue: 0
  },
  lifetimes: {
    attached() {
      this.setData({
        currentValue: this.format(this.data.value),
      });
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    observeValue() {
      const { value, currentValue } = this.data;

      if (!equal(value, currentValue)) {
        this.setData({ currentValue: this.format(value) });
      }
    },

    check() {
      const val = this.format(this.data.currentValue);
      if (!equal(val, this.data.currentValue)) {
        this.setData({ currentValue: val });
      }
    },

    isDisabled(type) {
      const {
        disabled,
        disablePlus,
        disableMinus,
        currentValue,
        max,
        min,
      } = this.data;

      if (type === 'plus') {
        return disabled || disablePlus || Number(currentValue) >= Number(max);
      }

      return disabled || disableMinus ||  Number(currentValue) <= Number(min);
    },

    onFocus(event) {
      this.triggerEvent('focus', event.detail);
    },

    onBlur(event) {
      const value = this.format(event.detail.value);
      this.emitChange(value);
      this.triggerEvent('blur', {
        ...event.detail,
        value,
      });
    },

    // filter illegal characters
    filter(value) {
      value = String(value).replace(/[^0-9.-]/g, '');

      if (this.data.integer && value.indexOf('.') !== -1) {
        value = value.split('.')[0];
      }

      return value;
    },

    format(value) {
      value = this.filter(value)
      // 如果为空字符串，那么设置为0，同时将值转为Number类型
      value = value === '' ? 0 : value
      // 对比最大最小值，取在min和max之间的值
      value = Math.max(Math.min(this.data.max, value), this.data.min)
      // 如果设定了最大的小数位数，使用toFixed去进行格式化
      if (this.data.decimalLength !== null) {
        value = value.toFixed(this.data.decimalLength)
      }
      return value
    },

    onInput(event) {
      const { value = '' } = event.detail || {};

      // allow input to be empty
      if (value === '') {
        return;
      }

      let formatted = this.filter(value);
      // limit max decimal length
      if (this.data.decimalLength!=null && formatted.indexOf('.') !== -1) {
        const pair = formatted.split('.');
        formatted = `${pair[0]}.${pair[1].slice(0, this.data.decimalLength)}`;
      }

      this.emitChange(formatted);
    },

    emitChange(value) {
      if (!this.data.asyncChange) {
        this.setData({ currentValue: value });
      }

      this.triggerEvent('change', value);
    },

    onChange() {
      const { type } = this;

      if (this.isDisabled(type)) {
        this.triggerEvent('overlimit', type);
        return;
      }

      const diff = type === 'minus' ? -this.data.step : +this.data.step;

      const value = this.format(this.add(+this.data.currentValue, diff));

      this.emitChange(value);
      this.triggerEvent(type);
    },
    // 对值扩大后进行四舍五入，再除以扩大因子，避免出现浮点数操作的精度问题
    add(num1, num2) {
      const cardinal = Math.pow(10, 10);
      return Math.round((num1 + num2) * cardinal) / cardinal
    },
    longPressStep() {
      this.longPressTimer = setTimeout(() => {
        this.onChange();
        this.longPressStep();
      }, 250);
    },

    onTap(event) {
      const { type } = event.currentTarget.dataset;
      this.type = type;
      this.onChange();
    },

    onTouchStart(event) {
      if (!this.data.longPress) {
        return;
      }
      clearTimeout(this.longPressTimer);

      const { type } = event.currentTarget.dataset;
      this.type = type;
      this.isLongPress = false;

      this.longPressTimer = setTimeout(() => {
        this.isLongPress = true;
        this.onChange();
        this.longPressStep();
      }, 600);
    },

    onTouchEnd() {
      if (!this.data.longPress) {
        return;
      }
      clearTimeout(this.longPressTimer);
    }
  }
})
